package cn.springcloud.fix.demo.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * https://maoqizhi.blog.csdn.net/article/details/110407987
 */
public class NIOServer {

    private static final Charset charset = Charset.forName("utf-8");

    private static Selector selector;

    static {
        try {
            selector = Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            // channel起手四句：ServerSocketChannel.open();  channel设置阻塞为false
            // channel.bind 端口号   channel.register(selector)
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(8080));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            new Reactor().start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class Reactor extends Thread {

        @Override
        public void run() {
            try {
                select();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void select() throws IOException {
            while (selector.select() > 0) {  //如果没有准备好的通道，这里会阻塞住，减少CPU消耗,有准备好的通过，马上使用
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        accept(key);
                    } else if (key.isReadable()) {
                        read(key);
                    }
                    iterator.remove();  //必须要从集合中移除！否则下次事件发生时不会被感知到
                }
            }
        }

        private void read(SelectionKey key) throws IOException {
            SocketChannel channel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(100);
            int num = channel.read(byteBuffer);
            if (num > 0) {
                byteBuffer.flip();
                String data = charset.decode(byteBuffer).toString();   // 解析出来
                System.out.println(data);   //打印出来
            } else if (num == -1) {
                // num=-1代表连接已关闭
                channel.close();
            }
        }

        private void accept(SelectionKey key) throws IOException {
            ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
            SocketChannel channel = serverChannel.accept();
            if (channel != null) {
                InetSocketAddress localAddress = (InetSocketAddress) channel.getLocalAddress();
                String hostName = localAddress.getHostName();
                System.out.println("接收到来自" + hostName + "的请求");
                channel.configureBlocking(false);
                //监听这个接收到的socket
                channel.register(selector, SelectionKey.OP_READ);  // 注册到客户端channel上面去
            }
        }
    }
}
